package server
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.utils.setInterval;
	
	import mx.collections.ArrayCollection;
	import mx.utils.StringUtil;
	
	import vo.RoomVO;

	public class RoomService extends EventDispatcher
	{
		private var _rooms:ArrayCollection = new ArrayCollection();
		
		private var url:String = "http://192.168.0.151:8080/HouseArchSimpleServer/database";
		
		public function RoomService()
		{
			setInterval(query, 6000);
		}
		
		public function query():void
		{
			var req:URLRequest = new URLRequest(url);
			req.method = URLRequestMethod.POST;
			var variable:URLVariables = new URLVariables();
			variable.operation  = "query";
			req.data = variable;
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onQueryResult);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onQueryError);
			loader.load(req);
		}
		
		/**
		 * 更新房间信息
		 */
		public function update(temp:String):void
		{
			var req:URLRequest = new URLRequest(url);
			req.method = URLRequestMethod.POST;
			var variable:URLVariables = new URLVariables();
			variable.operation  = "update";
			variable.room =  temp;
			req.data = variable;
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onQueryResult);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onQueryError);
			loader.load(req);
		}
		
		private function onQueryError(event:Event):void
		{
			event.target.removeEventListener(Event.COMPLETE, onQueryResult);
			event.target.removeEventListener(IOErrorEvent.IO_ERROR, onQueryError);
		}
		
		private function onQueryResult(event:Event):void
		{

			event.target.removeEventListener(Event.COMPLETE, onQueryResult);
			event.target.removeEventListener(IOErrorEvent.IO_ERROR, onQueryError);
			var data:String = event.target.data;
			if(data)
			{
				var roomDatas:Array = data.split("@");
				var length:int = roomDatas.length;
				var newRooms:Array = [];
				for(var i:int = 0; i < length; i++)
				{
					var item:String = roomDatas[i];
					if(StringUtil.trim(item))
					{
						var properties:Array = item.split(",");
						var id:String = properties[0];
						var room:RoomVO = getRoomById(id);
						if(room != null)
						{
							roomApply(room, properties);
							continue;
						}
						newRooms.push(roomApply(null, properties));
					}
				}
				if(newRooms != null && newRooms.length > 0)
				{
					rooms.source = rooms.source.concat(newRooms);
					rooms.refresh();
				}
				this.dispatchEvent(new Event("roomUpdated"));
			}
		}
		
		private function roomApply(room:RoomVO, properties:Array):RoomVO
		{
			if(room == null)
			{
				room = new RoomVO();
			}
			var names:Array = ["id", "floor", "size", "rent_out", "startDate", "endDate", "name", "customer"];
			for(var i:int = 0; i < names.length; i++)
			{
				var value:Object;
				if(String(names[i]).indexOf("Date") > 0)
				{
					value = StringUtil.trim(properties[i]);;
					value = parseString(value as String, "yyyy-mm-dd");
				}
				else
				{
					value = StringUtil.trim(properties[i]);;
				}
				room[names[i]] = value;//
			}
			return room;
		}
		
		public function getRoomById(id:String):RoomVO
		{
			for(var i:int = rooms.length - 1; i >= 0; i--)
			{
				var room:RoomVO = rooms.getItemAt(i) as RoomVO;
				if(room.id == id)
				{
					return room;
				}
			}
			return null;
		}

		public function get rooms():ArrayCollection
		{
			return _rooms;
		}

		public function set rooms(v:ArrayCollection):void
		{
			_rooms = v;
		}
		
		public static function parseString(value:String, formatStr:String):Date
		{
			var date:Date = new Date();
			formatStr  = formatStr.toLowerCase();
			//year
			var year:Number = parseTimeItem(value, formatStr, "y");
			var month:Number = parseTimeItem(value, formatStr, "m");
			var day:Number = parseTimeItem(value, formatStr, "d");
			var hour:Number = parseTimeItem(value, formatStr, "h");
			var minute:Number = parseTimeItem(value, formatStr, "n");
			var second:Number = parseTimeItem(value, formatStr, "s");
			var ms:Number = parseTimeItem(value, formatStr, "i");
			date.setUTCFullYear(year, month - 1, day);
			//date.setHours(hour, minute ,second, ms);
			return date;
		}
		
		private static function parseTimeItem(value:String, formatStr:String, timeItem:String):Number
		{
			var index:int = formatStr.indexOf(timeItem);
			var lastIndex:int = formatStr.lastIndexOf(timeItem);
			lastIndex  = formatStr.length + lastIndex;
			return parseInt(value.substring(index, lastIndex));
		}

	}
}